<?php
namespace Service;

class UserIncomeLog extends Base
{

    private $database = null;

    public function getDatabase()
    {
        if($this->database){
            return $this->database;
        }
        $this->database = $this->get(DATABASE_USERINCOMELOG);
        return $this->database;
    }

    public function addIncome($userId, $addOrSub, $type, $amount, $note = '', $more = [])
    {
        $userId = (int)$userId;
        if($userId < 0){
            return false;
        }
        if(!in_array($addOrSub, [ACCOUNT_ADD, ACCOUNT_SUB])){
            return false;
        }
        if(!checkAccountLogType($type)){
            return false;
        }
        if(!is_numeric($amount) || $amount == 0){
            return false;
        }
        $now = getDateTime();
        $amountAbs = abs($amount);
        $amountNegtive = 0 - $amountAbs;
        $insert = [
            'dry_user' => $userId,
            'dry_invited' => 0,
            'dry_type' => $type,
            'dry_amount' => ($addOrSub == ACCOUNT_ADD)?$amountAbs:$amountNegtive,
            'dry_order_no' => isset($more['orderNo'])?$more['orderNo']:'',
            'dry_month' => date('Ym', getTimestamp()),
            'dry_add_date' => $now['date'],
            'dry_add_time' => $now['date_time'],
            'dry_note' => $note
        ];
        return $this->add($insert);
    }

    public function hasIncome($userId, $orderNo)
    {
        $database = $this->getDatabase();
        $data = [
            'dry_user' => $userId,
            'dry_order_no' => $orderNo
        ];
        return $database->getOneByFields($data);
    }

    public function getList($userId, $page, $limit)
    {
        return $this->getDatabase()->getList($userId, $page, $limit);
    }

    public function getSum($userId, $typeIn = '', $month = '', $startDate = '', $endDate = '')
    {
        $total = $this->getDatabase()->getSum($userId, $typeIn, $month, $startDate, $endDate);
        return bcadd($total, 0, 2);
    }

    public function getByOrderNo($orderNo)
    {
        $database = $this->getDatabase();
        return $database->getOneByField('dry_order_no', $orderNo);
    }

}